package com.me.hippy.sdk.demo.chat

import android.animation.ValueAnimator
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.me.hippy.sdk.R
import com.me.hippy.sdk.demo.retrofitokhoot.api.ApiClient
import com.me.hippy.sdk.demo.retrofitokhoot.model.HttpResponse
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_demo_chat.*

class ChatActivity : FragmentActivity() {
    private lateinit var listAdapter: ListAdapter
    private val dataList = mutableListOf<String>()

    var canChange = true
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_demo_chat)
        initTestDatas()
        recyclerView.layoutManager = LinearLayoutManager(this)

        listAdapter = ListAdapter(dataList)
        recyclerView.adapter = listAdapter

        btn_send.setOnClickListener {
            sendMessage(et_input.text.toString())
            et_input.text.clear()

            ApiClient.instance.getList(et_input.text.toString())
                .subscribe(object : Observer<HttpResponse<Any>> {
                    override fun onSubscribe(d: Disposable?) {
                    }

                    override fun onNext(value: HttpResponse<Any>?) {
                        ToastUtils.showLong(JSON.toJSONString(value))
                        Log.e("ChatActivity========", "onNext:${JSON.toJSONString(value)}")
                    }

                    override fun onError(e: Throwable?) {
                        Log.e("ChatActivity========", "onError:${e?.message}")
                    }

                    override fun onComplete() {
                    }

                })

            sendMessage(et_input.text.toString())
            et_input.text.clear()


        }
        btn_add.setOnClickListener {
            canChange = false
            KeyboardUtils.hideSoftInput(et_input)
        }
        et_input.addTextChangedListener {
            if (TextUtils.isEmpty(it.toString())) {
                btn_add.visibility = View.VISIBLE
                btn_send.visibility = View.GONE
            } else {
                btn_add.visibility = View.GONE
                btn_send.visibility = View.VISIBLE
            }
        }

//        val keyboardChangeListener = KeyboardChangeListener(this)
//        keyboardChangeListener.mo14613a(this)

        enableTranslucentStatusBarEffects()

        KeyboardHelper.listen(this) { isShowed, keyboardHeight ->
            if (isShowed) {
                recyclerView.scrollToPosition(listAdapter.itemCount - 1)
            }
            if (canChange) {
//            val layoutParams = fl_keyboard.layoutParams
//            layoutParams.height = i
//            fl_keyboard.layoutParams = layoutParams
                animChange(fl_keyboard.layoutParams.height, keyboardHeight)
            } else {
                canChange = true
            }
        }
    }

    private fun sendMessage(msg: String) {
        listAdapter.addData(msg)
        recyclerView.scrollToPosition(listAdapter.itemCount - 1)
    }

    private fun initTestDatas() {
        for (i in 1..40) {
            dataList.add("初始数据>>$i")
        }
    }

    class ListAdapter : BaseQuickAdapter<String, ListAdapter.MyViewHolder> {
        constructor(data: MutableList<String>?) : super(0, data)

        override fun convert(holder: MyViewHolder, item: String) {
            holder.titleTv?.text = item
        }

        override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
            val titleTv = TextView(parent.context)
            titleTv.setPadding(
                ConvertUtils.dp2px(10f),
                ConvertUtils.dp2px(10f),
                ConvertUtils.dp2px(10f),
                ConvertUtils.dp2px(10f)
            )
            titleTv.setTextColor(0xff000000.toInt())
            val viewHolder = MyViewHolder(titleTv)
            viewHolder.titleTv = titleTv
            return viewHolder
        }

        class MyViewHolder : BaseViewHolder {
            var titleTv: TextView? = null

            constructor(view: View) : super(view)
        }
    }

    private var valueAnimator: ValueAnimator? = null
    private fun animChange(heightStart: Int, heightEnd: Int) {
        if (valueAnimator == null) {
            valueAnimator = ValueAnimator.ofInt(heightStart, heightEnd)
            valueAnimator?.duration = 120
            valueAnimator?.addUpdateListener {
                val layoutParams = fl_keyboard.layoutParams
                layoutParams.height = it.animatedValue as Int
                fl_keyboard.layoutParams = layoutParams
                if (it.animatedFraction == 1f) {
                    recyclerView.scrollToPosition(listAdapter.itemCount - 1)
                }
            }
        } else {
            valueAnimator?.setIntValues(heightStart, heightEnd)
        }
        valueAnimator?.start()
        Log.e("========", "heightStart=$heightStart,heightEnd=$heightEnd")
    }

    fun enableTranslucentStatusBarEffects() {
        if (Build.VERSION.SDK_INT >= 19) {
            val window = window
            val attributes = window.attributes
            attributes.flags = attributes.flags or FLAG_TRANSLUCENT_STATUS
            Log.e("=====", "attributes.flags=${attributes.flags}")
            window.attributes = attributes
        }
    }
}